package com.springboot_shopping.service.impl;

import com.springboot_shopping.Mapper.PictureMapper;
import com.springboot_shopping.entity.Picture;
import com.springboot_shopping.vo.PictureUploadRequest;
import com.springboot_shopping.vo.PictureUploadResponse;
import com.springboot_shopping.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {
    private final PictureMapper pictureMapper;

    @Value("${image.upload.path}")
    private String uploadPath;

    @Value("${image.access.url}")
    private String accessUrl;

    @Value("${image.allowed.types}")
    private String allowedTypes;

    public PictureServiceImpl(PictureMapper pictureMapper) {
        this.pictureMapper = pictureMapper;
    }

    public PictureUploadResponse uploadPicture(PictureUploadRequest request) {
        MultipartFile file = request.getFile();

        // 1. 验证文件是否为空
        if (file.isEmpty()) {
            return new PictureUploadResponse(null, null, null, "上传文件不能为空");
        }

        // 2. 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !allowedTypes.contains(contentType)) {
            return new PictureUploadResponse(null, null, null, "不支持的文件类型: " + contentType);
        }

        try {
            // 3. 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String newFilename = UUID.randomUUID() + fileExtension;      // 生成新的文件名

            // 4. 创建目标文件（使用Paths解决路径分隔符问题）
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs(); // 创建整个目录路径
            }

            File destFile = Paths.get(uploadPath, newFilename).toFile();

            // 5. 保存文件
            file.transferTo(destFile);

            // 6. 创建图片实体
            Picture picture = new Picture();
            picture.setTitle(request.getTitle());
            picture.setMemo(request.getMemo());

            // 确保URL以斜杠结尾
            String baseUrl = accessUrl.endsWith("/") ? accessUrl : accessUrl + "/";
            picture.setUrl(baseUrl + newFilename);

            picture.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
            picture.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
            picture.setUpdateAdminId(1L);

            // 7. 保存到数据库
            pictureMapper.insert(picture);

            // 8. 返回响应
            return new PictureUploadResponse(
                    picture.getId(),
                    picture.getTitle(),
                    picture.getUrl(),
                    "图片上传成功"
            );

        } catch (IOException e) {
            e.printStackTrace();
            return new PictureUploadResponse(null, null, null, "文件保存失败: " + e.getMessage());
        }
    }
}